#include "robotpubi.h"
#include <Ice/Ice.h>
#include <IceStorm/IceStorm.h>
#include "tmglobaldef.h"

RobotPubI::RobotPubI()
{
    g_pRobotNotify = new TmRobotNoty();
    g_pRobotNotify->start();
}

void RobotPubI::Notify(const std::string &strType, const std::string &strMsg, const Ice::Current &)
{
    g_pRobotNotify->sendNotify(strType, strMsg);
}

TmRobotNoty::TmRobotNoty()
{

}

void TmRobotNoty::run()
{
    Ice::StringSeq args;
    args.push_back("--Ice.Default.Locator=RobotIceGrid/Locator:tcp -p 4061");
    m_pIcComm = Ice::initialize(args);
    Ice::ObjectPrx objPrx = m_pIcComm->stringToProxy("PubCenter/TopicManager");

    g_topicMPrx = NULL;
    try{
        g_topicMPrx = IceStorm::TopicManagerPrx::checkedCast(objPrx);
    }
    catch( Ice::Exception& e )
    {
        qDebug()<<"TmRobotNoty get prx error:"<<e.what();
        return;
    }
    IceStorm::TopicPrx topicPrx;
    std::string topicName = "Notify";
    try
    {
        topicPrx = g_topicMPrx->retrieve(topicName);
    }
    catch(const IceStorm::NoSuchTopic&)
    {
        try
        {
            topicPrx = g_topicMPrx->create(topicName);
        }
        catch( const IceStorm::TopicExists& )
        {
            qDebug()<<"TmRobotNoty create Notify topic failed!";
            return;
        }
    }
    try{
        Ice::ObjectPrx pubPrx = topicPrx->getPublisher();
        m_pubNotifyPrx = Robot::PubPrx::uncheckedCast(pubPrx);
    }catch(...){
        qDebug()<<"g_pubNotifyPrx get failed!";
    }
    qDebug()<<"TmRobotNoty Run ok!";
    QThread::exec();
}

void TmRobotNoty::sendNotify(std::string strType, std::string strMsg)
{
    if( m_pubNotifyPrx ){
        m_pubNotifyPrx->Notify(strType, strMsg);
    }
}
